﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Models;
using HIWSystem.Common;
using System.Data;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;

namespace HIWSystem.ViewModel
{
    public class AddStationViewModel : ViewModelBase
    {
        public AddStationViewModel()
        {
            Messenger.Default.Register<string>(this, "CompleteStationUpdate", FillDataGridAsync);
        }
        #region 命令
        private RelayCommand loadPageCmd;

        public RelayCommand LoadPageCmd
        {
            get
            {
                if (loadPageCmd == null)
                {
                    loadPageCmd = new RelayCommand(LoadPage);
                }
                return loadPageCmd;
            }
            set { loadPageCmd = value; }
        }
        private RelayCommand addStationCmd;

        public RelayCommand AddStationCmd
        {
            get 
            {
                if (addStationCmd==null)
                {
                    addStationCmd = new RelayCommand(AddStation);
                }
                return addStationCmd; 
            }
            set { addStationCmd = value; }
        }
        private RelayCommand<StationsEntity> updateStationCmd;

        public RelayCommand<StationsEntity> UpdateStationCmd
        {
            get {
                if (updateStationCmd==null)
                {
                    updateStationCmd = new RelayCommand<StationsEntity>(UpdateStation);
                }
                return updateStationCmd; }
            set { updateStationCmd = value; }
        }
        private RelayCommand<StationsEntity> deleteStationCmd;

        public RelayCommand<StationsEntity> DeleteStationCmd
        {
            get {
                if (deleteStationCmd==null)
                {
                    deleteStationCmd = new RelayCommand<StationsEntity>(DeleteStation);
                }
                return deleteStationCmd; }
            set { deleteStationCmd = value; }
        }
        private RelayCommand unloadedPageCmd;

        public RelayCommand UnloadedPageCmd
        {
            get {
                if (unloadedPageCmd==null)
                {
                    unloadedPageCmd = new RelayCommand(UnloadedPage);
                }
                return unloadedPageCmd; }
            set { unloadedPageCmd = value; }
        }
        private RelayCommand windowClosingCommand;

        public RelayCommand WindowClosingCommand
        {
            get {
                if (windowClosingCommand==null)
                {
                    windowClosingCommand = new RelayCommand(()=> { Messenger.Default.Unregister(this); });
                }
                return windowClosingCommand; }
            set { windowClosingCommand = value; }
        }
        #endregion

        #region 属性
        private ObservableCollection<StationTypeEntity> stationTypeResource;
        /// <summary>
        /// 站位类型实体类集
        /// </summary>
        public ObservableCollection<StationTypeEntity> StationTypeResource
        {
            get { return stationTypeResource; }
            set { stationTypeResource = value; this.RaisePropertyChanged(() => StationTypeResource); }
        }
        private StationTypeEntity selectedStationTypeEntity;
        /// <summary>
        /// 选择的站位类型实体<ComboBox控件选中的内容>
        /// </summary>
        public StationTypeEntity SelectedStationTypeEntity
        {
            get { return selectedStationTypeEntity; }
            set { selectedStationTypeEntity = value; this.RaisePropertyChanged(() => SelectedStationTypeEntity); }
        }
        private string station="";
        /// <summary>
        /// 站位
        /// </summary>
        public string Station
        {
            get { return station; }
            set { station = value; this.RaisePropertyChanged(() => Station); }
        }
        private string stationDesc="";
        /// <summary>
        /// 站位描述
        /// </summary>
        public string StationDesc
        {
            get { return stationDesc; }
            set { stationDesc = value; this.RaisePropertyChanged(() => StationDesc); }
        }
        private ObservableCollection<StationsEntity> stationResource;
        /// <summary>
        /// 站位数据源<绑定到GridView>
        /// </summary>
        public ObservableCollection<StationsEntity> StationResource
        {
            get { return stationResource; }
            set { stationResource = value; this.RaisePropertyChanged(() => StationResource); }
        }
        private bool isFocusStationTextBox=true;
        /// <summary>
        /// 是否使站位文本框获得焦点
        /// </summary>
        public bool IsFocusStationTextBox
        {
            get { return isFocusStationTextBox; }
            set { isFocusStationTextBox = value; this.RaisePropertyChanged(() => IsFocusStationTextBox); }
        }

        private ObservableCollection<string> packingCheckFlagSource;
        /// <summary>
        /// 包装工序检查标记资源
        /// </summary>
        public ObservableCollection<string> PackingCheckFlagSource
        {
            get { return packingCheckFlagSource; }
            set { packingCheckFlagSource = value; this.RaisePropertyChanged(() => PackingCheckFlagSource); }
        }
        private string packingCheckFlag;
        /// <summary>
        /// 包装检查标记
        /// </summary>
        public string PackingCheckFlag
        {
            get { return packingCheckFlag; }
            set { packingCheckFlag = value; this.RaisePropertyChanged(() => PackingCheckFlag); }
        }
        private ObservableCollection<string> endCheckFlagSource;
        /// <summary>
        ///  入库检查标记资源
        /// </summary>
        public ObservableCollection<string> EndCheckFlagSource
        {
            get { return endCheckFlagSource; }
            set { endCheckFlagSource = value; this.RaisePropertyChanged(() => EndCheckFlagSource); }
        }

        private string endCheckFlag;
        /// <summary>
        /// 入库检查标记
        /// </summary>
        public string EndCheckFlag
        {
            get { return endCheckFlag; }
            set { endCheckFlag = value; this.RaisePropertyChanged(() => EndCheckFlag); }
        }

        #endregion

        #region 辅助方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadPage()
        {
            StationTypeResource = new ObservableCollection<StationTypeEntity> 
            { 
              new StationTypeEntity{Id=1,StationTypeCn="正常",StationTypeEn="Normal"},
              new StationTypeEntity{Id=1,StationTypeCn="质量",StationTypeEn="QC"},
              new StationTypeEntity{Id=1,StationTypeCn="测试",StationTypeEn="Test"}
            };
            PackingCheckFlagSource = new ObservableCollection<string> { "Y", "N" };
            EndCheckFlagSource = new ObservableCollection<string> { "Y", "N" };
            this.FillDataGridAsync("");//初始化数据网格数据
        }
        private void AddStation()
        {
            string retMsg = string.Empty;//返回存储过程返回状态信息
            DataTable dtStation = new DataTable();
            StationsEntity stationsEntity = new StationsEntity() 
            { 
                Station= Station.Trim().ToUpper(),
                StationDesc=this.StationDesc,
                StationType= SelectedStationTypeEntity?.StationTypeEn??"",
                PackingCheckFlag=this.PackingCheckFlag??"",
                EndCheckFlag=this.EndCheckFlag??""
            };
            retMsg=BusinessProcess.AddStation(stationsEntity, out dtStation);
            if (retMsg.Split('|')[0] == "NO") //表示添加失败
            {
                MessageBox.Show(retMsg.Split('|')[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                if (dtStation.Rows.Count>0)
                {
                    StationResource = new ObservableCollection<StationsEntity>();
                    for (int i = 0; i < dtStation.Rows.Count; i++)
                    {
                        StationResource.Add
                          (
                            new StationsEntity
                            {
                                Id=Convert.ToInt32(dtStation.Rows[i]["Id"].ToString()??"0"),
                                Station = dtStation.Rows[i]["Station"].ToString(),
                                StationDesc = dtStation.Rows[i]["Description"].ToString(),
                                StationType = dtStation.Rows[i]["Type"].ToString(),
                                PackingCheckFlag = dtStation.Rows[i]["PackingCheckFlag"].ToString(),
                                EndCheckFlag = dtStation.Rows[i]["EndCheckFlag"].ToString(),
                                CreateAt = dtStation.Rows[i]["CreateAt"].ToString()
                            }
                          ) ;
                    }
                    MessageBox.Show("添加成功", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                    //清空文本框中的内容
                    this.Station = "";
                    this.StationDesc = "";
                    this.PackingCheckFlag = "";
                    this.EndCheckFlag = "";
                    this.isFocusStationTextBox = true;
                }
            }
        }
        /// <summary>
        /// 填充数据到数据网格中
        /// </summary>
        private async void FillDataGridAsync(string msg)
        {
            DataTable dt = new DataTable();
            ObservableCollection<StationsEntity> tmpStationResource = new ObservableCollection<StationsEntity>();
            await Task.Run(() => {
                dt = BusinessProcess.GetStations(EnumStationType.All);
                if (dt.Rows.Count > 0)
                {
                    Application.Current.Dispatcher.BeginInvoke((Action)(() => {
                        StationResource = new ObservableCollection<StationsEntity>();
                    }));
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        tmpStationResource.Add
                          (
                            new StationsEntity
                            {
                                Id = Convert.ToInt32(dt.Rows[i]["Id"].ToString() ?? "0"),
                                Station = dt.Rows[i]["Station"].ToString(),
                                StationDesc = dt.Rows[i]["Description"].ToString(),
                                StationType = dt.Rows[i]["Type"].ToString(),
                                PackingCheckFlag = dt.Rows[i]["PackingCheckFlag"].ToString(),
                                EndCheckFlag = dt.Rows[i]["EndCheckFlag"].ToString(),
                                CreateAt = dt.Rows[i]["CreateAt"].ToString()
                            }
                          );
                    }
                    Application.Current.Dispatcher.BeginInvoke((Action)(() => {
                        StationResource = tmpStationResource;
                    }));
                }
            });
            if (msg!="")
            {
                ViewManager.Close("UpdateStation");
            }
           
        }
        /// <summary>
        /// 更新站位
        /// </summary>
        /// <param name="obj">站位实体</param>
        private void UpdateStation(StationsEntity obj)
        {
            string retMsg = string.Empty;//返回的状态信息
            string[] arrayMsg = new string[2];
            if (obj != null)
            {
                retMsg = BusinessProcess.EmployeeIsHaveModuleAuthority("AC");
                arrayMsg = retMsg.Split('|');
                //Y表示有权限
                if (arrayMsg[0] == "Y")
                {
                    ViewManager.Show("UpdateStation");
                    Messenger.Default.Send<StationsEntity>(obj, "UpdateStationInfo");
                }
                else
                {
                    MessageBox.Show(arrayMsg[1], "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        
        }
        /// <summary>
        /// 删除站位
        /// </summary>
        /// <param name="obj"></param>
        private void DeleteStation(StationsEntity obj)
        {
            string retMsg = string.Empty;//返回的状态信息
            string[] arrayMsg = new string[2];
            if (obj != null)
            {
                retMsg = BusinessProcess.EmployeeIsHaveModuleAuthority("AD");
                arrayMsg = retMsg.Split('|');
                //Y表示有权限
                if (arrayMsg[0] == "Y")
                {
                    //确定用户是否要删除，防止误删
                    MessageBoxResult boxResult = MessageBox.Show(string.Format("确定要删除站位【{0}】吗？", obj.Station), "软件温馨提示!", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (boxResult == MessageBoxResult.Yes)
                    {
                        if (BusinessProcess.DeleteStationInfo(obj))
                        {
                            StationResource.Remove(obj);
                        }
                        else
                        {
                            MessageBox.Show("删除失败", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show(arrayMsg[1], "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        private void UnloadedPage()
        {
            Messenger.Default.Unregister(this);
        }
        #endregion

    }
}
